package com.geek.javase.ch17.work.tcpwork.tcp7;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.CopyOnWriteArrayList;

/*
 *@Date 2025/11/4
 *@Author wangpeng
 *@Description
 * Tasker充当话务员的角色，将一个客户端发送给服务端的信息转发给其他所有的客户端
 */
public class Tasker implements Runnable{
    private static CopyOnWriteArrayList<Socket> clients = new CopyOnWriteArrayList<Socket>();
    private Socket socket;
    public Tasker(Socket socket, CopyOnWriteArrayList<Socket> clients) {
        this.socket = socket;
        this.clients = clients;
    }
    @Override
    public void run() {
        try{
            //将一个客户端发送给服务端的信息转发给其他所有的客户端
            while(true){
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String str = br.readLine();
                if (str.equals("exit")){
                    System.out.println(socket.getRemoteSocketAddress()+"下线了！");
                    break;
                }
                for (Socket client : clients) {
                    if(client != socket){
                        PrintWriter pw = new PrintWriter(client.getOutputStream());
                        pw.println(socket.getRemoteSocketAddress()+":"+str);
                        pw.flush();
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
